package com.ct.web.controllers;

import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.validation.BindException;
import org.springframework.validation.Validator;
import org.springframework.validation.ValidationUtils;
import org.springframework.beans.propertyeditors.PropertiesEditor;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.ParseException;

/**
 * Created by IntelliJ IDEA.
 * User: nmkravchenko
 * Date: 26.01.2010
 * Time: 19:17:18
 * To change this template use File | Settings | File Templates.
 */
public class BaseController extends MultiActionController {

    @Override
    protected void initBinder(HttpServletRequest req, ServletRequestDataBinder binder) throws Exception {
        binder.registerCustomEditor(Date.class, (new PropertiesEditor(){
            @Override
            public void setAsText(String s) throws IllegalArgumentException {
                if(StringUtils.isNotBlank(s)){
                    DateFormat df = new SimpleDateFormat("MM.dd.yyyy");
                    try{
                        Date date = df.parse(s);
                        setValue(date);
                    }catch(ParseException pe){
                        throw new IllegalArgumentException(pe.toString());
                    }
                }else{
                    return;
                }
            }
        }));
    }
    
    protected BindException bindObject(HttpServletRequest request,
                                       Object command,
                                       Validator validator) throws Exception {
        ServletRequestDataBinder binder = createBinder(request, command);
        binder.bind(request);

        BindException errors = new BindException(command, getCommandName(command));
        if (validator != null && validator.supports(command.getClass())) {
           ValidationUtils.invokeValidator(validator, command, errors);
        }

        return errors;
    }


}
